const app = getApp();
const Controller = require('../controllers/controllers.js').controller;
const WxParse = require('../Common/wxParse/wxParse.js');
let myaudio;
let dsq;

Page({
  data: {
    id:"",
    detail:'',
    content:'',
    msg:"",
    title:'',
    shareimg:'',
    sharepath:'',
    source:'',
    page:1,
    pageSize:10,
    isEnd:false,
    commentlistdata:[],
    userid:'',
    lryid:'',
    parentId:'',
    userNick:'',
    isfocus:false,
    isonce:true,
    isfirst:true,
    isloading:true,
    ispayend:false,
    currentTime:"0:00",
    percentSj:0,
    bof:true,
    playtext:"../../images/bo.png",
    maxV:100
  },
  onLoad: function (options) {
    
    // this.videoContext = wx.createVideoContext('articlevideo')
    this.videoContext = wx.createInnerAudioContext('articlevideo')
    
    

    if(options.id){
      this.setData({
        id: options.id || ''
      })
    }
    if(options.parentid){
      app.globalData.parentid=options.parentid
    }
  },
  
  onShow: function () {
    
    // this.contentdetail()
    
    
  },
  onUnload(){
      console.log('关闭页面')
      myaudio.pause();
  },
  onReady() {
       this.contentdetail()
   
   
    

  },
  AudioInit(){
    myaudio = wx.createInnerAudioContext(); //音乐播放实例
    myaudio.title = this.data.detail.title;
    myaudio.epname = this.data.detail.authorName;
    myaudio.src = this.data.detail.audioUrl;
    

    myaudio.onCanplay(()=> {
      // 必须。可以当做是初始化时长
      myaudio.duration;
      // 必须。不然也获取不到时长
      setTimeout(() => {
        this.setData({
          maxV:myaudio.duration
        })
      }, 200)
    })


    myaudio.onPlay(() => {
        this.setData({
          bof:false,
          playtext:"../../images/tin.png"
        })
        clearInterval(dsq)
        myaudio.duration
        
        this.setData({
          maxV:myaudio.duration
        })

        dsq=setInterval(()=>{
          
          if(this.data.maxV == 0 ||this.data.maxV == 100){
              this.setData({
                maxV:myaudio.duration
              })
          }

          this.setData({
            currentTime:this.millisToMinutesAndSeconds(myaudio.currentTime*1000),
            percentSj:myaudio.currentTime
          })
        },500)

        
        


        console.log('录音播放中');
        
    })
    myaudio.onStop(() => {
      clearInterval(dsq)

        console.log('录音暂停');
        this.setData({
            bof:true,
            playtext:"../../images/bo.png"
        })

    })
    myaudio.onEnded(() => {
      clearInterval(dsq)

      console.log('录音播放停止');
      this.setData({
          bof:true,
          playtext:"../../images/bo.png",
          maxV:100,
          currentTime:"0:00",
          percentSj:0
      })
    })



  },
  play(){
    if(this.data.bof){
        clearInterval(dsq)

        myaudio.play();
        this.setData({
          bof:false,
          playtext:"../../images/tin.png"
        })
    }else{
        clearInterval(dsq)
        myaudio.pause();
        this.setData({
          bof:true,
          playtext:"../../images/bo.png"
        })
    }
  },
  press(event){
      clearInterval(dsq)
      myaudio.pause();
      const position=event.detail.value;
      myaudio.seek(position)
      myaudio.play()

  },
  millisToMinutesAndSeconds(millis) {
    var minutes = Math.floor(millis / 60000);
    var seconds = ((millis % 60000) / 1000).toFixed(0);
    return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
  },
  bindended(){
    this.setData({
      ispayend:true
    })
  },
  replay(){
    this.videoContext.play()
    this.setData({
      ispayend:false
    })
  },
  contentdetail(){
    Controller.contentdetail({contentId:this.data.id}).then(res=>{
      if(res.data.baseData){
        
        
        res.data.baseData.detail = JSON.stringify(res.data.baseData.detail).replace(/<img/gi, "<img class='richImg' style='width:auto!important;height:auto!important;max-height:100%;width:100%;'");
        res.data.baseData.detail = JSON.parse(res.data.baseData.detail);
        var content=res.data.baseData.detail
        if(content){
          WxParse.wxParse('content', 'html', content, this, 5);
        }
        this.setData({
          detail:res.data.baseData
        })
        wx.setNavigationBarTitle({
          title: this.data.detail.title 
        })
        if(this.data.isfirst){
          this.action(3,true)
          this.setData({
            isfirst:false
          })
        }
        
        this.setData({
          page:1,
          pageSize:10,
          isEnd:false,
          commentlistdata:[],
        })
        this.commentlist()
      }
      this.setData({
        isloading:false
      })

      //音频初始化
      this.AudioInit()
      // console.log(this.data.detail.categoryId)

    })
  },
  contentdetail1(){
    Controller.contentdetail({contentId:this.data.id}).then(res=>{
      if(res.data.baseData){
        this.setData({
          detail:res.data.baseData
        })
        var content=res.data.baseData.detail
        if(content){
          WxParse.wxParse('content', 'html', content, this, 5);
          res.data.baseData.detail = JSON.stringify(res.data.baseData.detail).replace(/<img/gi, "<img class='richImg' style='width:auto!important;height:auto!important;max-height:100%;width:100%;'");
          res.data.baseData.detail = JSON.parse(res.data.baseData.detail);
        }
      }
    })
  },
  commentlist(){
    var data={
      bodyType:this.data.detail.source,
      bodyId:this.data.id,
      page:this.data.page,
      pageSize:this.data.pageSize,
    }
    Controller.commentlist({bodyId:this.data.id,bodyType:this.data.detail.source}).then(res=>{
      if(res.data.baseData && res.data.baseData.list.length>0){
        for(var item of res.data.baseData.list){
          item.more=false
        }
        this.setData({
          commentlistdata:this.data.commentlistdata.concat(res.data.baseData.list),
        })

      
      }
      if(res.data.baseData.lastPage){
        this.setData({
          isEnd:res.data.baseData.lastPage
        })
      }
      
    })
  },
  morelry(e){
    var lists=this.data.commentlistdata;
    var index=e.currentTarget.dataset.index
    lists[index].more=true
    this.setData({
      commentlistdata:lists
    })
  },
  onReachBottom(){
    if(this.data.isEnd){
      return
    }else{
      this.setData({
        page:this.data.page+1
      })
      this.commentlist()
    }
    
  },
  changemsg(e){
    var value=e.detail.value || ''
    if(value){
      this.setData({
        msg: value
      })
    }
  },
  zan(e){
    if(this.data.detail.hasLike==0){
      this.action(1,true)
    }else{
      var that=this;
      wx.showModal({
        title: '提示',
        content: '是否取消点赞',
        success (res) {
          if (res.confirm) {
            that.action(1,false)
          } else if (res.cancel) {
          }
        }
      })
    }
  },
  sendmsg(e){
    var data={}
    console.log(this.data.lryid)
    if(this.data.lryid){
      data={
        content:this.data.msg,
        bodyType:this.data.detail.source,
        bodyId:this.data.lryid,
        parentId:this.data.parentId,
        level:2,
        toUserId:this.data.userid
      }
    }else{
      data={
        content:this.data.msg,
        bodyType:this.data.detail.source,
        bodyId:this.data.id
      }
    }
    
    Controller.comment(data).then(res=>{
      wx.showToast({
        title:"评论成功"
      })
      this.setData({
        page:1,
        pageSize:10,
        isEnd:false,
        commentlistdata:[],
        msg:''
      })
      this.action(6,true)
      this.commentlist()
    })
  },
  lry(e){
    this.setData({
      lryid:e.currentTarget.dataset.id,
      userid:e.currentTarget.dataset.userid,
      parentId:e.currentTarget.dataset.parentid,
      userNick:e.currentTarget.dataset.usernick,
      isfocus:true
    })
  },
  inputblur(){
    var that=this
    setTimeout(()=>{
      that.setData({
        lryid:"",
        userid:"",
        parentId:'',
        userNick:'',
        isfocus:false
      })
    },500)
    
  },
  commentAction(e){
    let dataset= e.currentTarget.dataset||{}
    let index=dataset.index

    console.log('dataset.like',dataset.like)

   if(dataset.id){
      
   let params={}
   
    params.rId=dataset.id

    params.type=1
     
    params.source=9  // 主体对象的类型，1是名医内容，2是专家内容，3.养生视频，4养生资讯，5是商城，6食谱，7名医，8专家
    params.contentType=this.data.detail.type  //内容类

    let commentlistdata=this.data.commentlistdata

    if(Number(dataset.like)===0){
      Controller.action(params).then(res=>{
      
        if(res.code==0){
          
          commentlistdata[index].hasLike=Number(dataset.like)===0?1:0
          commentlistdata[index].likeActionId=res.data.baseData

  
          this.setData({
            commentlistdata
          })
  
        }
      })
   
    }else{
      Controller.delAction({actionId:dataset.aid}).then(res=>{
        if(res.code==0){

          
          commentlistdata[index].hasLike=Number(dataset.like)===0?1:0
  
          this.setData({
            commentlistdata
          })
  
        }
      })
    }
    
  }
    
  },
  action(type,isbool){
    var data={}
    if(isbool){
      data.rId=this.data.id
      data.type=type  //类型，1是点赞，2是关注，3.浏览,5分享，6发布,7.签到8.观看视频
      data.source=this.data.detail.source  // 主体对象的类型，1是名医内容，2是专家内容，3.养生视频，4养生资讯，5是商城，6食谱，7名医，8专家
      data.contentType=this.data.detail.type  //内容类型，1是文章，2是视频，3是食谱，4.课程，5是商品
      Controller.action(data).then(res=>{
        if(type==1 && isbool){
          wx.showToast({
            title:"点赞成功"
          })
          this.contentdetail1()
        }
      })
    }else{
      data.actionId=this.data.detail.likeActionId
      Controller.delAction(data).then(res=>{
          wx.showToast({
            title:"取消成功"
          })
          this.contentdetail1()
      })
    }
  },
  bindplay(e){
    if(this.data.isonce){
      this.action(8,true)
      this.setData({
        isonce:false
      })
    }
    
  },
  vip(e){
    wx.navigateTo({
      url:"/pages/Me/vip"
    });
  },
  //支付 1是名医，2是专家，3.养生视频，4养生资讯
  pay() {
    if(app.globalData.isios){
      wx.showToast({
        title:"ios提示不能支付",
        icon:"none"
      })
      return
    }
    var ordertype=this.data.detail.source==3?3:this.data.detail.source==4?1:this.data.detail.source==1?1:this.data.detail.source==2?1:1;
    wx.navigateTo({
      url:"/pages/mall/order?ordertype="+ordertype+"&id="+this.data.id+"&type=other&source=资讯"
    });
  },
  onShareAppMessage: function (e) {
    let title = this.data.detail.title || '';
    let imageUrl = this.data.detail.iconImgUrl || '';
    let path=app.getCurrentPageUrlWithArgs()
    let obj = {
      title,
      imageUrl,
      path,
      success: function (res) {},
      fail(err) {}
    }
    this.action(5,true)
    return obj
  },
  onShareTimeline: function(res){
    let title = this.data.detail.title || '';
    let imageUrl = this.data.detail.iconImgUrl || '';
    let path=app.getCurrentPageUrlWithArgs()
    let obj = {
      title,
      imageUrl,
      path,
      success: function (res) {},
      fail(err) {}
    }
    this.action(5,true)
    return obj
  },

})